<script setup lang="ts">
import type { WorkBenchRes } from "./echarts/type.ts"
import * as THREE from "three"
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"
import { GUI } from "three/examples/jsm/libs/lil-gui.module.min.js"
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js"
import { CSS2DObject, CSS2DRenderer } from "three/examples/jsm/renderers/CSS2DRenderer.js"
import { onMounted, reactive, ref } from "vue"
import { getBuildingInfoApi, getWorkBenchAPI } from "@/pages/visualization/echarts/api"
import BarChart from "@/pages/visualization/echarts/BarChart.vue"
import ParkInfo from "@/pages/visualization/echarts/ParkInfo.vue"
import PieChart from "@/pages/visualization/echarts/PieChart.vue"

// ------------------ 类型定义 ------------------
interface BuildingItem {
  id: number
  buildingname: string
  roof: string | string[]
  mesh?: THREE.Mesh | THREE.Group // 可选，方便后续控制模型
}

const info = reactive<WorkBenchRes["data"]>({} as WorkBenchRes["data"])

// ------------------ Three.js 初始化 ------------------
const modelContainer = ref<HTMLDivElement>()
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000)
const renderer = new THREE.WebGLRenderer({ antialias: true })
const labelRenderer = new CSS2DRenderer()
labelRenderer.setSize(window.innerWidth, window.innerHeight)
labelRenderer.domElement.style.position = "absolute"
labelRenderer.domElement.style.top = "0px"
labelRenderer.domElement.style.pointerEvents = "none"
const controls = new OrbitControls(camera, renderer.domElement)
const light = new THREE.DirectionalLight(0xFFFFFF, 1)
const gui = new GUI()

// 这里 reactive 里是 BuildingItem[]
const buildings = [
  {
    id: "1d1190c1-8d69-4e6f-b4ee-1fd45a315016",
    buildName: "办公楼1栋",
    roof: "房顶_7"
  },
  {
    id: "5682e989-7aa8-4729-996c-4acd90bc5fac",
    buildName: "办公楼2栋",
    roof: "房顶_12"
  },
  {
    id: "397e0566-9731-46b7-b80b-ed6d2313524b",
    buildName: "办公楼3栋",
    roof: "房顶_6"
  },
  {
    id: "39d54c5a-5454-4b5c-a3c3-8cf42af7553d",
    buildName: "办公楼4栋",
    roof: "房顶_13"
  },
  {
    id: "dd54bae3-6bc3-491f-ac33-280a0e950992",
    buildName: "办公楼5栋",
    roof: "房顶_8"
  },
  {
    id: "08668309-93d9-4c7e-8381-903aaaca51d0",
    buildName: "办公楼6栋",
    roof: "房顶_14"
  },
  {
    id: "32260190-65df-41c8-bfd5-77f848e47614",
    buildName: "办公楼7栋",
    roof: "房顶_15"
  },
  {
    id: "7cb39d6a-09ca-4521-a422-123920ad7f88",
    buildName: "办公楼8栋",
    roof: "房顶_16"
  },
  {
    id: "25fa4c7c-0949-4b2d-bcf9-288f7f0836e2",
    buildName: "办公楼9栋",
    roof: "房顶_17"
  },
  {
    id: "6db0a639-b9a2-48b8-a1de-7ed1feee0216",
    buildName: "办公楼16栋",
    roof: [
      "房顶_22",
      "房顶_23"
    ]
  },
  {
    id: "25fa4c7c-0949-4b2d-bcf9-288f7f0836e2",
    buildName: "办公楼9栋",
    roof: "房顶_17"
  },
  { id: "fbca66a1-bdb3-4aed-8910-8a084e232b42", buildName: "办公楼10栋", roof: "房顶_18" },
  {
    id: "7b13cfe1-0bbd-40f3-82bd-5d9353cc824a",
    buildName: "办公楼11栋",
    roof: "房顶_19"
  },
  {
    id: "7e3cb1d5-9b78-4c91-8dbd-7ba35f6a001d",
    buildName: "办公楼12栋",
    roof: "房顶_20"
  },
  {
    id: "bc6001a1-2dbc-4558-9c1e-2d9799975003",
    buildName: "办公楼13栋",
    roof: "房顶_21"
  },
  {
    id: "4ef0dd12-18f2-49aa-80e9-65389cb1635c",
    buildName: "办公楼14栋",
    roof:
      ["房顶", "房顶_1", "房顶_2", "房顶_3"]
  },
  {
    id: "34244aff-752c-416f-b3a9-b6298ad39983",
    buildName: "办公楼15栋",
    roof: [
      "房顶_4",
      "房顶_5"
    ]
  },
  {
    id: "6db0a639-b9a2-48b8-a1de-7ed1feee0216",
    buildName: "办公楼16栋",
    roof: [
      "房顶_22",
      "房顶_23"
    ]
  },
  {
    id: "e55d7934-f6ab-43d9-88ca-f1899f74cb1f",
    buildName: "办公楼17栋",
    roof: [
      "房顶_24",
      "房顶_25"
    ]
  },
  {
    id: "0c3f5910-e38b-4efd-a1db-573dc7d6aaa4",
    buildName: "办公楼18栋",
    roof: [
      "房顶_26",
      "房顶_27"
    ]
  },
  {
    id: "8fcb105e-c196-4c9a-8cc0-e9a28d269e7f",
    buildName: "办公楼19栋",
    roof: [
      "房顶_28",
      "房顶_29"
    ]
  },
  {
    id: "89264b98-a5a7-4135-8a74-c0e81075ea55",
    buildName: "办公楼20栋",
    roof: [
      "房顶_30",
      "房顶_31"
    ]
  },
  {
    id: "7f2c9686-bbea-40c2-b720-443f7299b644",
    buildName: "办公楼21栋",
    roof: "房顶_10"
  },
  {
    id: "165ac1fe-db1b-4191-91be-4e4765e04fe5",
    buildName: "办公楼22栋",
    roof: "房顶_9"
  },
  {
    id: "da290ede-ade3-41f0-92aa-f747659e4684",
    buildName: "办公楼23栋",
    roof: "房顶_32"
  },
  {
    id: "68c1b7a3-0f3d-44b5-9802-295a94f2b2a5",
    buildName: "办公楼24栋",
    roof: "房顶_33"
  },
  {
    id: "7b6c01b6-cdd7-4a9a-9c37-b6e278cbd4c4",
    buildName: "办公楼25栋",
    roof: "房顶_34"
  },
  { id: "33420cb3-c1d3-4384-b34b-6cadf469f2d3", buildName: "办公楼26栋", roof: "房顶_11" },
  {
    id: "7887422e-28cb-4c28-b6c1-919dd981e059",
    buildName: "办公楼27栋",
    roof: "房顶_35"
  },
  {
    id: "0e69b1b6-58b0-4add-8e82-fb6c740d040b",
    buildName: "办公楼28栋_",
    roof: "房顶_36"
  }

]
const park = [
  {
    id: "9c47efc7-0013-407a-a546-7f8ecaac5791",
    name: "停车场1号",
    rect: "Rectangle",
    isHire: true,
    line: ["线_1", "线_2"]
  },
  {
    id: "7d644480-dec8-4e5f-901e-16f7fc1f4f56",
    name: "停车场2号",
    rect: "Rectangle_1",
    isHire: false,
    line: ["线_4", "线_5"]
  },
  {
    id: "7661d56f-4c20-46d1-8784-11fae639a3d8",
    name: "停车场3号",
    rect: "Rectangle_2",
    isHire: true,
    line: ["线_7", "线_8"]
  },
  { id: "5b35440d-04bb-498c-8f4c-3cc9d3a7b2ac", name: "停车场4号", rect: "Rectangle_3", isHire: false, line: ["线_10", "线_11"] },
  {
    id: "2d89a3e9-07b9-402b-9cd3-ee4c3934f37b",
    name: "停车场5A",
    rect: "Rectangle_4",
    isHire: false,
    line: ["线_13", "线_14"]
  },
  {
    id: "d106153e-14d0-44f4-a68d-d61914f1f167",
    name: "停车场5B",
    rect: "Rectangle_5",
    isHire: true,
    line: ["线_15"]
  },
  {
    id: "5e85943f-3951-475a-b88d-61b9e3ffa912",
    name: "停车场6A",
    rect: "Rectangle_6",
    isHire: true,
    line: ["线_17", "线_18"]
  },
  {
    id: "dc194a04-a00c-40cc-8678-97cbd00f36ef",
    name: "停车场6B",
    rect: "Rectangle_7",
    isHire: false,
    line: ["线_19"]
  },
  {
    id: "ecd096e5-c39a-4e3f-8530-22b9ace8dfd0",
    name: "停车场_7号",
    rect: "Rectangle_8",
    isHire: true,
    line: ["线_20"]
  },
  {
    id: "bf2c9625-efe6-4138-81ff-03fceab9831",
    name: "停车场8号",
    rect: "Rectangle_9",
    isHire: true,
    line: ["线_23", "线_24", "线_26", "线_27", "线_29", "线_30", "线_32", "线_33", "线_35", "线_36"]
  },
  {
    id: "072bc23c-62ab-4b93-a199-285f15a3d746",
    name: "停车场9号",
    rect: "rectangle_10",
    isHire: false,
    line: ["线_38", "线_39", "线_41", "线_42"]
  },
  {
    id: "d69434b5-efb7-4b27-8b9b-ca37314a3208",
    name: "停车场10号",
    rect: "Rectangle_11",
    isHire: true,
    line: ["线_44", "线_45"]
  },
  {
    id: "3cf890f8-7348-4bdd-b9f7-1ef8a35319e9",
    name: "停车场11号",
    rect: "Rectangle_12",
    isHire: false,
    line: ["线_47", "线_48"]
  },
  {
    id: "7563486a-83ca-49b3-94e3-fd332738ba93",
    name: "停车场12号",
    rect: "Rectangle_13",
    isHire: false,
    line: ["线_50", "线_51"]
  },
  {
    id: "520e0a7c-c473-48f5-98a8-f9a5afc55987",
    name: "停车场13号",
    rect: "Rectangle_14",
    isHire: true,
    line: ["线_53", "线_54"]
  },
  {
    id: "5d2fffde-fa4b-426a-90f5-107c4b405f33",
    name: "停车场14号",
    rect: "Rectangle_15",
    isHire: false,
    line: ["线_56", "线_57"]
  },
  {
    id: "7f6e0a4c-a032-44ce-a2f2-19d368e03929",
    name: "停车场15号",
    rect: "Rectangle_16",
    isHire: true,
    line: ["线_59", "线_60"]
  },
  {
    id: "551fa9S6-a329-44dd-bb53-ae36bd41d235",
    name: "停车场16号",
    rect: "Rectangle_17",
    isHire: true,
    line: ["线_62", "线_63"]
  },
  {
    id: "9e005858-c271-498f-a5a9-c805ae8066dd",
    name: "停车场17号",
    rect: "Rectangle_18",
    isHire: true,
    line: ["线_65", "线_66"]
  },
  {
    id: "33e9ela8-d8d9-4583-ad3f-46fc6f139cc7",
    name: "停车场18号",
    rect: "Rectangle_19",
    isHire: true,
    line: ["线_67"]
  },
  {
    id: "3817b8b6-5ca9-4c6a-8368-23badf3b603b",
    name: "停车场19号",
    rect: "Rectangle_20",
    isHire: true,
    line: ["xian"]
  }

]
light.position.set(1000, 10000, 1000)
controls.enableDamping = true
controls.dampingFactor = 0.05
renderer.setClearColor(0xB9D3FF, 1)
renderer.shadowMap.enabled = true
renderer.shadowMap.type = THREE.PCFSoftShadowMap

// ------------------ API 数据 ------------------
async function getInfo() {
  const res = await getWorkBenchAPI()
  Object.assign(info, res.data)
  console.log(info)
}
function createBuildingLabel(data) {
  const div = document.createElement("div")
  div.className = "building-label"

  div.innerHTML = `
    <div class="label-title">${data.name || "未知建筑"}</div>
    <div class="label-item">面积：${data.area ?? "暂无"}㎡</div>
    <div class="label-item">楼层：${data.floors ?? "暂无"}层</div>
    <div class="label-item">租户：${data.rentEnterpriseName ?? "暂无"}</div>
  `

  return new CSS2DObject(div)
}
// ------------------ 模型加载 ------------------
onMounted(() => {
  getInfo()

  if (modelContainer.value) {
    renderer.setSize(window.innerWidth, window.innerHeight)
    modelContainer.value.appendChild(renderer.domElement)
    modelContainer.value.appendChild(labelRenderer.domElement)
  }

  camera.position.set(2000, 2000, 2000)
  camera.lookAt(0, 0, 0)
  scene.add(light)

  const loader = new GLTFLoader()
  loader.load(
    "/spline-model.glb",
    (gltf) => {
      console.log("模型加载完成:", gltf.scene)

      // 遍历模型
      gltf.scene.traverse((obj: any) => {
        if (obj.isMesh) {
          obj.castShadow = true
          obj.receiveShadow = true
        }
      })
      const no_Material = new THREE.MeshStandardMaterial({ color: new THREE.Color(0x409EFF) })
      const yes_Material = new THREE.MeshStandardMaterial({ color: new THREE.Color(0xFF6600) })

      console.log("收集到的办公楼信息：", buildings)
      buildings.forEach(async (item) => {
        const res = await getBuildingInfoApi(item.id)
        const div = createBuildingLabel(res.data)
        div.visible = false
        const building = gltf.scene.getObjectByName(item.buildName)
        if (building) {
          div.position.set(0, 50, 0)
          building.add(div)
        }
        if (res.data.status == 0) {
          if (item.roof instanceof Array) {
            item.roof.forEach((roof) => {
              const fd = gltf.scene.getObjectByName(roof)
              if (fd) fd.material = no_Material
            })
          } else {
            const fd = gltf.scene.getObjectByName(item.roof)
            if (fd) fd.material = no_Material
          }
        } else {
          if (item.roof instanceof Array) {
            item.roof.forEach((roof) => {
              const fd = gltf.scene.getObjectByName(roof)
              if (fd) fd.material = yes_Material
            })
          } else {
            const fd = gltf.scene.getObjectByName(item.roof)
            if (fd) fd.material = yes_Material
          }
        }
      })

      modelContainer.value?.addEventListener("click", (e) => {
        const px = e.offsetX
        const py = e.offsetY
        // 屏幕坐标转标准设备坐标
        const x = (px / window.innerWidth) * 2 - 1
        const y = -(py / window.innerHeight) * 2 + 1
        const raycaster = new THREE.Raycaster()
        raycaster.setFromCamera(new THREE.Vector2(x, y), camera)
        const intersects = raycaster.intersectObjects(gltf.scene.children, true)
        console.log("点击了模型:", intersects[0])
        if (intersects.length > 0) {
          intersects[0].object.parent.parent.traverse((obj) => {
            if (obj instanceof CSS2DObject) {
              obj.visible = !obj.visible
              console.log(obj)
            }
          })
        }
      })
      park.forEach(async (item) => {
        const rectAngle = gltf.scene.getObjectByName(item.rect)
        if (rectAngle) rectAngle.material = new THREE.MeshStandardMaterial({ color: new THREE.Color(0xFFFFFF), opacity: item.isHire ? 0.6 : 0.2, transparent: true })
      })

      scene.add(gltf.scene)
    },
    undefined,
    (error) => {
      console.error("加载模型失败:", error)
    }
  )

  // ------------------ 动画循环 ------------------
  function animate() {
    requestAnimationFrame(animate)
    controls.update()
    renderer.render(scene, camera)
    labelRenderer.render(scene, camera)
  }
  animate()

  // ------------------ 监听窗口变化 ------------------
  window.addEventListener("resize", () => {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
  })
})
</script>

<template>
  <div>
    <div class="echartsContainer">
      <h2 style="margin:0;">
        智慧园区
      </h2>
      <div class="parkInfo infoContainer">
        <ParkInfo :data="info.base" />
      </div>
      <div class="barChart container">
        <BarChart :data="info.parkIncome" />
      </div>
      <div class="pieChart container">
        <PieChart :data="info.parkIndustry" />
      </div>
    </div>
    <div class="modelContainer" ref="modelContainer" />
  </div>
</template>

<style scoped lang="scss">
:deep(.building-label) {
  height: 100px;
  width: 100px;
  color: white;
}
.echartsContainer {
  width: 30%;
  position: absolute;
}
.modelContainer {
  width: 100vw;
  height: 100vh;
}
.header {
  text-align: center;
  margin-bottom: 30px;
  .title {
    color: white;
    font-size: 28px;
    font-weight: 600;
    margin: 0;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }
}

.content-grid {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 20px;
  height: calc(100% - 120px);
}

.info-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.charts-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.chart-item {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  flex: 1;
}

.section-title,
.chart-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 2px solid #667eea;
}

// 响应式设计
@media (max-width: 1200px) {
  .content-grid {
    grid-template-columns: 1fr;
    gap: 15px;
  }

  .charts-section {
    flex-direction: row;
  }
}

@media (max-width: 768px) {
  .visualization-container {
    padding: 15px;
  }

  .header .title {
    font-size: 24px;
  }

  .charts-section {
    flex-direction: column;
  }

  .chart-item,
  .info-section {
    padding: 15px;
  }
}
</style>
